package shard;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自己实现 应用层分片（一致性 hash）
 * 如果你不是 Redis 集群，只是多个单点实例，需要像以前的 ShardedJedis 那样分布 key，可以自己写个
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2025/8/25 16:50
 * @updateUser:     MI
 * @updateTime:     2025/8/25 16:50
 * @updateRemark:   修改内容
 * @version:        1.0
 */
public class ShardingByHash {

    private final Map<Integer, JedisPool> poolMap = new HashMap<>();
    private final List<String> servers = Arrays.asList("127.0.0.1:6379", "192.168.110.36:6379");

    public ShardingByHash() {
        for (int i = 0; i < servers.size(); i++) {
            String[] hp = servers.get(i).split(":");
            poolMap.put(i, new JedisPool(new JedisPoolConfig(), hp[0], Integer.parseInt(hp[1])));
        }
    }

    private JedisPool getPool(String key) {
        int index = Math.abs(key.hashCode()) % servers.size();
        return poolMap.get(index);
    }

    public void set(String key, String value) {
        try (Jedis jedis = getPool(key).getResource()) {
            jedis.set(key, value);
        }
    }

    public String get(String key) {
        try (Jedis jedis = getPool(key).getResource()) {
            return jedis.get(key);
        }
    }

    public static void main(String[] args) {
        ShardingByHash sharding = new ShardingByHash();
        for (int i = 0; i < 100; i++) {
            sharding.set("k" + i, "" + i);
        }
        for (int i = 0; i < 100; i++) {
            System.out.println("取到值：" + sharding.get("k" + i));
        }
    }
}
